package com.hlx.herostory;

import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

public class GameMsgDecoder extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof BinaryWebSocketFrame)) {
            return;
        }

        // WebSocket 二进制消息会通过 HttpServerCodec 解码成 BinaryWebSocketFrame 类对象
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
        ByteBuf byteBuf = frame.content();

        byteBuf.readShort(); // 读取消息的长度，即读取一个short类型的值，因为websocket会带上消息长度，故跳过该2个字节
        short msgCode = byteBuf.readShort(); // 读取消息的编号  例如02，即对应 WhoElseIsHereCmd（还有谁在场）

        // 读取消息体
        byte[] msgBody = new byte[byteBuf.readableBytes()]  ;
        byteBuf.readBytes(msgBody);

        Message.Builder msgBuilder = GameMsgRecognizer.getBuilderByMsgCode(msgCode);
        assert msgBuilder != null;
        msgBuilder.clear();
        msgBuilder.mergeFrom(msgBody);
        Message cmd = msgBuilder.build();

        if (null != cmd) {
            // ctx.pipline().fireChannelRead(msg) 从头节点向下传播事件
            // 从当前节点向下传播事件  
            ctx.fireChannelRead(cmd);
        }
    }
}
